/* eslint-disable no-useless-concat */
interface Row{
    errorFieldList: number[]
    [propName: string]: string | number[]
}
interface Column{
    prop: string
    label: string
    width: string
    // eslint-disable-next-line no-unused-vars
    formatter?: (row: Row, column:{property:string}) => string
}
const getStyle = (column:Column, row:Row, height:number, colIndex:number):string => {
    let css = `
        height: ${height}pt;
        line-height: ${height}pt;
        width: ${parseInt(column.width, 10) || 200}px;
        font-size: 11pt;
        text-align: center;
    `
    if (column.prop === 'errorMsg' || row.errorFieldList.indexOf(colIndex - 1) !== -1) css += 'color: red;'
    return css
}

const getTd = (column:Column, row:Row, height:number, colIndex: number):string => {
    if (column.formatter) {
        // + '\t' 是为了转成字符串
        return `<td style="${getStyle(column, row, height, colIndex)}">${column.formatter(row, { property: column.prop }) || '' + '\t'}</td>`
    }
    return `<td style="${getStyle(column, row, height, colIndex)}">${row[column.prop] || '' + '\t'}</td>`
}

export default (data:Row[], columns:Column[], fileName = '导出表', height = 20) => {
    if (!columns.length) return

    const worksheet = 'Sheet1'
    let html = `
    <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
        <head>
            <!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>${worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
        </head>
        <body>
            <table>
                <thead>
                    <tr>`
    columns.forEach((item) => {
        html += `<th style="font-size: 11pt; height: ${height}pt; line-height: ${height}pt;">${item.label || ''}</th>`
    })
    html += '</tr></thead><tbody>'

    data.forEach((row:Row, rowIndex:number) => {
        html += '<tr>'
        columns.forEach((col, colIndex) => {
            html += getTd(col, row, height, colIndex)
        })
        html += '</tr>'
    })
    html += '</tbody></table></body></html>'

    const link = document.createElement('a')
    link.href = `data:text/csv;charset=utf-8,\ufeff${encodeURIComponent(html)}`
    // 两种不同的方法
    // link.href = URL.createObjectURL(new Blob([html], { type: 'application/vnd.ms-excel' }))
    link.download = `${fileName}.xls`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
}
